//
//  FirmwareUpgradeController.swift
//  DaRings
//
//  Created by 易先生 on 2022/10/31.
//

import UIKit
import MYModule
import CRPSmartRing
import Moya


open class FirmwareUpgradeController: BaseViewController {
    

    /// 固件升级类型
    public var otaType: OTAProvider.FileType = .normal
    
    /// 用来判断断连前是否正在固件升级
    private var isUpgrade = false
    
    public weak var timer: Timer?
    
    private var mac: String?
    
    public var fileInfo: OTAProvider.FileInfo? {
        
        didSet {
            
            upgradeButton.isHidden = false
        }
        
    }
    
    private var currentVersion: String? {
        
        didSet {
            
        
            guard let currentVersion = currentVersion else {
                return
            }
            
            descLabel.text = "firmware_current_version".language(with: [currentVersion])
            
            #if DEBUG
            
            #else
            
            upgradeButton.isHidden = true
            
            #endif
            
            
        }
        
    }
    
    private var provider = OTAProvider()
    
    private let progressView = View()
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.removeTimer()
        BluetoothManager.shared.stopUpgrade()
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        addNotifaction()

        info()
    }
    
    open func addNotifaction() {

        NotificationCenter.default.rx.notification(.kReceiveUpgredeNotification).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] in

                self?.notifactionAction(noti: $0)

        }).disposed(by: rx.disposeBag)


    }

    open func notifactionAction(noti: Notification) {

        guard let dict = noti.userInfo, let model = dict["result"] as? NKReceiveUpgredeModel  else { return }

        print("固件上传进度")
        print(model.progress)

        let multiplied = CGFloat(model.progress)/100.0

        self.progressView.snp.remakeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(self.upgradeButton.snp.width).multipliedBy(multiplied)
        }
        UIView.animate(withDuration: 0.1) {
            self.progressView.layoutIfNeeded()
        }

        if model.progress >= 100 {
            self.descLabel.text = "firmware_upgrade_upgrade_success".language
            self.upgradeButton.isUserInteractionEnabled = true
            self.upgradeButton.isHidden = true
            self.isUpgrade = false
            
            UIApplication.shared.isIdleTimerDisabled = self.isUpgrade
            // 删除本地保存
            OTAProvider.FileInfo.remove(of: self.otaType)
            
            UIAlertController.showOkAlert(title: "", message: "firmware_upgrade_upgrade_success".language, in: self) {
                self.navigationController?.popToRootViewController(animated: true)
            }
        }
    }


    open func info() {
        
        let diviceInfo = DeviceInfo.current()
        mac = diviceInfo.adress ?? ""
        currentVersion = diviceInfo.versoin ?? ""
        
        // 查看本地
        guard let fileInfo = self.fileInfo else {
            
            // 没有先请求
            self.request()
            
            return
        }
        
        
        // 本地有直接显示固件升级
        self.fileInfo = fileInfo
        
    }

    open func request() {

        BluetoothManager.shared.isConnectedForConnectState {

            guard let mac = self.mac, let version = self.currentVersion else {
                return
            }

            let apiTargetType = self.otaType.APITargetType(mac: mac, version: version)

            self.provider.upgrade(target: apiTargetType) { fileINfo in

                guard let fileINfo = fileINfo else {
                    /// 是最新版了
                    return
                }

                self.fileInfo = fileINfo


            } failure: { error in

                log.debug(error)

            }

        }

    }

    /// 下载固件
    open func download() {
        
        guard let fileInfo = self.fileInfo else { return }
        
        if BluetoothManager.shared.bluetoothState != .poweredOn || BluetoothManager.shared.deviceState != .connected {
            return
        }

        self.upgradeButton.isUserInteractionEnabled = false

        DispatchQueue.main.async {
            self.progressView.snp.remakeConstraints { make in
                make.left.top.bottom.equalToSuperview()
                make.width.equalTo(0)
            }
        }

        self.isUpgrade = true
        UIApplication.shared.isIdleTimerDisabled = self.isUpgrade

        provider.download(fileInfo: fileInfo) { progress in
            log.debug("当前下载进度:\(progress.progress)")

        } sucess: { fileINfo in
            log.debug("下载成功")

        } failure: { error in
            log.debug("下载固件失败")
            
            self.resetUI()
            UIAlertController.showAlertOk(title: "firmware_download_fail".language, message: "", in: self)
        }


    }

    open override func makeUI() {
        super.makeUI()

        self.navigation.bar.backgroundColor = UIColor.background
        view.backgroundColor = UIColor.background
        
        upgradeButton.isHidden = true

        progressView.isUserInteractionEnabled = false
        progressView.cornerRadius = 25.0
        progressView.backgroundColor = UIColor.theme

        upgradeButton.addTarget(self, action: #selector(upgradeAction), for: .touchUpInside)
        
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        
        UIApplication.shared.isIdleTimerDisabled = self.isUpgrade

        view.addSubview(titleView)
        view.addSubview(resetStackView)
        view.addSubview(upgradeButton)
        upgradeButton.addSubview(progressView)
        upgradeButton.sendSubviewToBack(progressView)


        resetStackView.addArrangedSubview(iconImage)
        resetStackView.addArrangedSubview(descLabel)

        titleView.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        resetStackView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }

        upgradeButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-72)
            make.leading.equalToSuperview().offset(50)
            make.trailing.equalToSuperview().offset(-50)
            make.height.equalTo(50)
        }

        progressView.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalToSuperview()
        }
    }

    open override func bindViewModel() {
        super.bindViewModel()

        
        NotificationCenter.default.rx.notification(Notification.Name.kDeviceStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
            guard let self = self else { return }
            guard let result = notification.userInfo as? [String: Any] else { return}
            guard let state = result["result"] as? CRPState else { return }
            switch state {
            case .disconnected:
                if self.isUpgrade {
                    UIAlertController.showOkAlert(title: "firmware_upgrade_fail".language, message: "dialog_firmware_reset_ble_powered_off_patiently".language, in: self) {
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            case .connected:
                self.resetUI()
            default:
                break
            }
        }).disposed(by: rx.disposeBag)


        NotificationCenter.default.rx.notification(Notification.Name.kBluetoothStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
            guard let self = self else { return }
            guard let result = notification.userInfo as? [String: Any] else { return}
            guard let state = result["result"] as? CRPBluetoothState else { return }
            switch state{
            case .poweredOff:
                UIAlertController.showOkAlert(title: "ble_disable".language, message: "", in: self) {
                    self.navigationController?.popViewController(animated: true)
                    self.resetUI()
                }
                self.addTimer()
                
                break
                
            case .poweredOn:
                
                self.removeTimer()
                
                break


            default:
                break
            }


        }).disposed(by: rx.disposeBag)

        NotificationCenter.default.rx.notification(.kReceiveLocationPermissionNotification).take(until: self.rx.deallocated).subscribe(onNext: { [weak self] notification in
            guard let self = self else { return }
            LocationManager.shared.authLocationPermission {

            } closed: {

            } cancel: {
                self.navigationController?.popViewController(animated: true)
            }
        }).disposed(by: rx.disposeBag)

    }
    
    open override func backAction() {
        if self.isUpgrade {
            UIAlertController.showAlertOk(title: "".language, message: "dialog_firmware_upgrade_wait_patiently".language, in: self)
            return
        } else {
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
            self.navigationController?.popViewController(animated: true)
        }
    }

    @objc open func upgradeAction() {

        guard let currentBattery = BluetoothManager.shared.currentBattery else { return }

        if currentBattery <= 30 {
            UIAlertController.showAlertOk(title: "firmware_upgrade_dialog_title".language, message: "firmware_upgrade_dialog_hint".language, in: self)
        } else {

            self.upgradeButton.isUserInteractionEnabled = false

            // 开始下载
            self.download()
        }
        


    }

    private func addTimer() {
        log.debug("设置定时器")
        self.removeTimer()
        if timer == nil {
            timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true, block: {[weak self] _ in
                guard let self = self else { return }
                UIAlertController.showOkAlert(title: "firmware_upgrade_fail".language, message: "firmware_file_error".language, in: self) {
                    self.navigationController?.popViewController(animated: true)
                }

            })
        }
    }

    private func removeTimer() {
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }



    private func resetUI() {
        DispatchQueue.main.async {
            self.progressView.snp.remakeConstraints { make in
                make.left.top.bottom.equalToSuperview()
                make.width.equalToSuperview()
            }
        }

        self.isUpgrade = false
        self.upgradeButton.isUserInteractionEnabled = true
        UIApplication.shared.isIdleTimerDisabled = self.isUpgrade
    }

    
// MARK: - lazy load

    private lazy var titleView: TopTitleView = {
        let titleView = TopTitleView()
        titleView.configTitle(title: "firmware_upgrade_title".language)
        return titleView
    }()


    private lazy var resetStackView: StackView = {
        let resetStackView = StackView()
        resetStackView.axis = .vertical
        resetStackView.spacing = 44
        resetStackView.alignment = .center
        return resetStackView
    }()

    private lazy var iconImage: ImageView = {
        let iconImage = ImageView()
        iconImage.image = UIImage(named: "ic_user_firmware_upgrade_checking")
        return iconImage
    }()

    private lazy var descLabel: Label = {
        let descLabel = Label()
        descLabel.textColor = UIColor.assist_222222
        descLabel.numberOfLines = 0
        descLabel.text = "device_checking_upgrade".language
        descLabel.font = Fonts.systemFont(ofSize: 16)
        return descLabel
    }()


    private lazy var upgradeButton: Button = {
        let upgradeButton = Button()

        let backImage = UIImage.imageWithColor(UIColor.theme)

        upgradeButton.setBackgroundImage(backImage, for: .normal)
        upgradeButton.setBackgroundImage(backImage, for: .highlighted)
        upgradeButton.setBackgroundImage(backImage, for: .selected)
        upgradeButton.setBackgroundImage(backImage, for: .disabled)

        upgradeButton.setTitleColor(UIColor.assist_FFFFFF, for: .normal)
        upgradeButton.setTitle("firmware_upgrade_latest_version".language, for: .normal)
        upgradeButton.titleLabel?.font = Fonts.systemFont(ofSize: 16)

        upgradeButton.cornerRadius = 25.0

        return upgradeButton
    }()

}
